<?php

function getParm($key,$default) {
    return isset($_GET[$key]) ? $_GET[$key] : $default;
}

// demoi.csv.php
// header('Content-type: text/csv');
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

$id = getParm('id','1');
$variable = getParm('var','0014');
$span = getParm('span','r');
$limit = getParm('limit','1440');
 
$db = include 'dbiConnect.php';
$sql = "SELECT `timestamp`, `value` FROM `readings` 
  WHERE `variable` = '0014'  AND timespan = 'r' AND device_id = 1
  ORDER BY `timestamp` DESC LIMIT 1440";
$sql = "SELECT `timestamp`, `value` FROM `readings` 
  WHERE `variable` = ?  AND timespan = ? AND device_id = ?
  ORDER BY `timestamp` DESC LIMIT $limit";
// http://devzone.zend.com/article/686
$stmt = $db->prepare($sql);
// $stmt->bind_param('s', $content['mac']); 
$stmt->bind_param('ssi', $variable, $span, $id); 
$stmt->execute();
$stmt->bind_result($timestamp,$value); 
while ($stmt->fetch()) { 
    $row = array('timestamp' => $timestamp, 'value' => $value);
    $rows[] = $row;
}
$stmt->close();
$db->close();
$n = count($rows);
for ($i=0; $i<$n; $i++) {
    $row = $rows[$n-$i-1];
    $datetime = $row['timestamp'];
    $value = $row['value'];
    echo '"'.$datetime.'",'.$value."\n";
}
/*
SELECT timestamp  FROM `readings` WHERE `variable` = '0014' ORDER BY timestamp desc limit 20

SELECT * FROM readings WHERE timestamp IN (
SELECT timestamp  FROM `readings` WHERE `variable` = '0014' ORDER BY timestamp desc limit 20)
ORDER BY timestamp asc
#1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' 

SELECT * FROM (
  SELECT * FROM readings WHERE variable = '0014' ORDER BY timestamp desc LIMIT 20
}
ORDER BY timestamp ASC
 
 */
?>
